import { withRouter } from "next/router";
import { useState, useEffect } from "react";
import { message, Empty } from "antd";
// css
import styles from "@/styles/CommonPersonal.module.scss";
// 组件
import Breadcrumb from "@/components/Breadcrumb";
import Aside from "@/pages_components/personal/Aside";
import Spin from "@/components/Spin";
import Pagination from '@/pages_components/components/Pagination';
import CouponItem from '@/pages_components/components/CouponItem';
// api
import { couponList, receiveCoupon } from '@/api/coupon';

const MyCoupon = ({ router }) => {
    
    const filter_list = [
        { name: '未领取', value: '1', active: true },
        { name: '未使用', value: '2' },
        { name: '已使用', value: '3' },
        { name: '已过期', value: '4'}
    ]
    const { query: { state } } = router;
    const [loading, setLoading] = useState(false);
    const [filters, setFilters] = useState(filter_list);
    const [status, setStatus] = useState(state || '1');
    const [list, setList] = useState([]);
    const [total, setTotal] = useState(0);

    useEffect(() => {
        if(status !== '1'){
            changeFilter(1)
        }else{
            doSearch({
                status: status
            })
        }
    }, []);

    // 切换filter
    function changeFilter(idx) {
        for (let i = 0; i < filters.length; i++) {
            const filter = filters[i];
            filter.active = false;
            if(idx === i){
                filter.active = true;
                setFilters([...filters]);
                setStatus(filter.value);
                doSearch({
                    status: filter.value
                })
            }
        }
    }
    // 筛选优惠券
    function onPageChange(curr) {
        doSearch({
            pageNo: curr,
            status: status
        })
    }
    // 获取优惠券
    function doSearch({ status, curr = 1 }) {
        const params = {
            state: status, // 1 2 3 4
            pageNo: curr,
            pageSize: 10
        }
        setLoading(true)
        couponList(params).then(res => {
            const { data, code } = res;
            if(code === 0 && data.records){
                const { totalCount } = data;
                setTotal(totalCount);
                setList([...data.records]);
            }
            setLoading(false);
        })
    }
    // 领取优惠券
    function receiveCouponFn(item) {
        setLoading(true);
        receiveCoupon({
            ids: [item.userOfCouponId]
        }).then(res => {
            const { code } = res;
            if(code == 0){
                changeFilter(1);
            }
            setLoading(false);
        })
    }

    // Compoent
    const filterComp = (
        <ul className={styles['filters']}>
            {
                filters.map((item, index) => <li className={item.active ? styles['active']:''} onClick={() => {changeFilter(index)}} key={index}>{item.name}</li>)
            }
        </ul>
    )

    return (
        <div className={styles["personal-page"]}>
            {/* loading */}
            <Spin loading={loading} />
            <div className="max-content">
                {/* 面包屑 */}
                <Breadcrumb
                    params={[
                        { name: "个人中心", url: "/personal" },
                        { name: "优惠券", url: "/personal/coupon" },
                    ]}
                />
                <div className={styles["wrapper"]}>
                    {/* 左侧 */}
                    <Aside />
                    {/* 内容 */}
                    <section className={[styles["content"], styles["coupon-content"]].join(" ")} >
                        { filterComp }
                        <div className={styles['filters-list']}>
                            {
                                !list.length 
                                ? <div className={styles['empty']}>
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="持续关注我们，领券机会多多~" />   
                                  </div>
                                : list.map((item,index) => <CouponItem data={item} receiveCouponFn={receiveCouponFn} key={index} />)
                            }
                        </div>
                    </section>
                </div>
                <div className={styles['pagination']}>
                    <Pagination onChange={onPageChange} size={10} total={total} />
                </div>
            </div>
      </div>
    )
}

export default withRouter(MyCoupon);